import { _decorator, Component, EventTouch, input, Input, math, Node, quat, Quat, v3, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('CameraControl')
export class CameraControl extends Component {
    
    @property(Node)

    target: Node = null;

    public yMinLimit = -90;//相机向下最大角度

    public yMaxLimit = 90;//相机向上最大角度

    private targetX = 0;

    private targetY = 0;

    private xSpeed = 25;

    private ySpeed = 12;

    private disance: Vec3 = v3();

    start() {

        let angles = this.node.eulerAngles;

        this.targetX = angles.y;

        this.targetY = angles.x;

        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);

        Vec3.subtract(this.disance, this.node.worldPosition, this.target.worldPosition);

        this.disance = v3(0,0,this.disance.length());

    }

    private onTouchMove(touch: EventTouch) {

        this.targetX -= touch.getDeltaX() * this.xSpeed * 0.02;

        this.targetY -= touch.getDeltaY() * this.ySpeed * 0.02;

        this.targetY = this.ClampAngle(this.targetY, this.yMinLimit, this.yMaxLimit);
    }

    private _quat = quat();

    private _vec3 = v3();

    update (deltaTime: number) {

        Quat.fromEuler(this._quat, this.targetY, this.targetX, 0);

        Vec3.transformQuat(this._vec3, this.disance, this._quat);

        Vec3.add(this._vec3, this.target.worldPosition.clone(), this._vec3);

        this.node.worldPosition = this._vec3.clone();

        this.node.worldRotation = this._quat.clone();

    }

    ClampAngle(angle, min, max) {

        if (angle < -360) angle += 360;

        if (angle > 360) angle -= 360;

        return math.clamp(angle, min, max);

    }
}


